import torch
import torch.nn as nn

from torch.hub import load_state_dict_from_url
from torchvision import transforms

model_urls = {
    "vgg16": "https://download.pytorch.org/models/vgg16-397923af.pth",
}


class VGG(nn.Module):
    def __init__(self, features, num_classes=1000, init_weights=True, dropout=0.5):
        super(VGG, self).__init__()
        self.features = features
        self.avgpool = nn.AdaptiveAvgPool2d((7, 7))
        self.classifier = nn.Sequential(
            nn.Linear(512 * 7 * 7, 4096),
            nn.ReLU(True),
            nn.Dropout(p=dropout),
            nn.Linear(4096, 4096),
            nn.ReLU(True),
            nn.Dropout(p=dropout),
            nn.Linear(4096, num_classes),
        )
        if init_weights:
            for m in self.modules():
                if isinstance(m, nn.Conv2d):
                    nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
                    if m.bias is not None:
                        nn.init.constant_(m.bias, 0)
                elif isinstance(m, nn.BatchNorm2d):
                    nn.init.constant_(m.weight, 1)
                    nn.init.constant_(m.bias, 0)
                elif isinstance(m, nn.Linear):
                    nn.init.normal_(m.weight, 0, 0.01)
                    nn.init.constant_(m.bias, 0)

    def forward(self, x):
        x = self.features(x)
        x = self.avgpool(x)
        x = torch.flatten(x, 1)
        x = self.classifier(x)
        return x


def make_layers(cfg, batch_norm=False):
    layers = []
    in_channels = 3
    for v in cfg:
        if v == "M":
            layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
        else:
            conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
            if batch_norm:
                layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]
            else:
                layers += [conv2d, nn.ReLU(inplace=True)]
            in_channels = v
    return nn.Sequential(*layers)


cfgs = {
    "D": [64, 64, "M", 128, 128, "M", 256, 256, 256, "M", 512, 512, 512, "M", 512, 512, 512, "M"],
}


def vgg16(pretrained=True, progress=True, num_classes=5):
    model = VGG(make_layers(cfgs['D']))
    if pretrained:
        state_dict = load_state_dict_from_url(model_urls['vgg16'], model_dir='../model', progress=progress)
        model.load_state_dict(state_dict)
    if num_classes != 1000:
        model.classifier = nn.Sequential(
            nn.Linear(512 * 7 * 7, 4096),
            nn.ReLU(True),
            nn.Dropout(p=0.5),
            nn.Linear(4096, 4096),
            nn.ReLU(True),
            nn.Dropout(p=0.5),
            nn.Linear(4096, num_classes),
        )
    return model


def get_trained_my_vgg16():
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model = vgg16(True, True, 5)
    model.load_state_dict(torch.load('../model/new_vgg16_trained.pth', device))
    return model


def judge_by_model(image, model=None, resize_shape=(224, 224)):
    if model is None:
        device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        model = vgg16(True, True, 5)
        model.load_state_dict(torch.load('../model/new_vgg16_trained.pth', device))
    model.eval()
    transform = transforms.Compose([transforms.ToTensor(), transforms.Resize(resize_shape)])
    image = transform(image)
    image = torch.reshape(image, (1, 3, 224, 224))
    with torch.no_grad():
        out = model(image)[0,]
    index = int(out.argmax(0))
    predict = torch.nn.functional.softmax(out, dim=0)
    if predict[index] < 0.7:
        index = -1
    return index, predict[index]
